﻿using AutoMapper;
using Enter.Admin.Dtoes;
using Enter.Admin.Entities;
using Enter.Admin.Filters;
using Enter.Admin.Models;
using Enter.Admin.Models.DataTables;
using Enter.Admin.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Enter.Admin.Configs.Validator;
using FluentValidation.AspNetCore;

namespace Enter.Admin.Controllers
{
    [TypeFilter(typeof(ActionFilter), Arguments = new object[] { ActionRole.Admin })]
    public class UserController : BaseController
    {
        public UserController(ILogger<UserController> logger, IFreeSql fsql, IMapper mapper):base(logger, fsql, mapper)
        {
        }
        // GET: UserController
        public ActionResult Index()
        {
            List<SelectListItem> RoleSelectList = new List<SelectListItem>() { new SelectListItem { Value = "0", Text = "全部" } };
            _fsql.Select<Role>().Where(t => t.IsDeleted == false).ToList().ForEach(r =>
            {
                RoleSelectList.Add(new SelectListItem { Value = r.Id.ToString(), Text = r.RoleName });
            });
            return View(RoleSelectList);
        }

        [HttpPost]
        public IActionResult Index([FromBody] DataTablesParameters<EmploySearchModel> model)
        {
            var select_data = _fsql.Select<Employ>().Include(a => a.Role)//.WithSql("SELECT a.*, b.RoleName FROM Employ a JOIN Role b ON a.RoleId = b.Id")
                .WhereIf(model.Data.RoleId > 0, t => t.RoleId == model.Data.RoleId)
                .WhereIf(!string.IsNullOrWhiteSpace(model.Data.UserName), t => t.UserName.Contains(model.Data.UserName))
                .WhereIf(!string.IsNullOrWhiteSpace(model.Data.TrueName), t => t.TrueName.Contains(model.Data.TrueName))
                .WhereIf(!string.IsNullOrWhiteSpace(model.Data.Email), t => t.Email.Contains(model.Data.Email))
                .WhereIf(!string.IsNullOrWhiteSpace(model.Data.Phone), t => t.Phone.Contains(model.Data.Phone))
                .WhereIf(model.Data.State > -1, t => t.State == model.Data.State)
                .Where(t => t.IsDeleted == false)
                .Count(out var total).Skip(model.Start).Take(model.Length).ToList();
            var data = _mapper.Map<List<EmployModel>>(select_data);
            return Json(new DataTablesResult<EmployModel>(model.Draw, total, total, data));
        }

        // GET: UserController/Detail/5
        public ActionResult Detail(int id)
        {
            return View();
        }

        // POST: UserController/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([CustomizeValidator(RuleSet = "Create")] EmployModel model)
        {
            if (_fsql.Select<Employ>().Where(t => t.UserName == model.UserName && t.IsDeleted == false).Any())
            {
                return Json(new ResponseResult<string>(false, "用户名已存在."));
            }
            var new_employ = new Employ()
            {
                Id = 0,
                RoleId = model.RoleId,
                UserName = model.UserName,
                Password = Crypto.Md5(model.Password),
                TrueName = model.TrueName,
                Email = model.Email??string.Empty,
                Phone = model.Phone ?? string.Empty,
                State = (int)model.State,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                IsDeleted = false,
            };
            _fsql.Insert<Employ>(new_employ).ExecuteAffrows();
            // 更新;
            BaseController.UpdateUserList(_fsql);
            return Json(new ResponseResult<string>(true, "创建成功."));
        }

        // GET: UserController/Edit/5
        public ActionResult Edit(int id)
        {
            List<SelectListItem> RoleSelectList = new List<SelectListItem>();
            _fsql.Select<Role>().Where(t => t.IsDeleted == false).ToList().ForEach(r =>
            {
                RoleSelectList.Add(new SelectListItem { Value = r.Id.ToString(), Text = r.RoleName });
            });
            RoleSelectList[0].Selected = true;
            ViewData["RoleSelectList"] = RoleSelectList;
            if (id == 0)
            {
                return View(new Employ());
            }
            var model = _fsql.Select<Employ>(new { Id = id }).ToOne();
            if (model == null || model.IsDeleted)
            {
                return View("Error", new ErrorViewModel() { StatusCode = 404 });
                // 404
            }
            return View(model);
        }

        // POST: UserController/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(long id, EmployModel model)
        {
            if (_fsql.Select<Employ>().Where(t => t.Id != id && t.UserName == model.UserName && t.IsDeleted == false).Any())
            {
                return Json(new ResponseResult<string>(false, "用户名已存在."));
            }
            _fsql.Update<Employ>()
                .SetIf(model.RoleId > 0, a => a.RoleId, model.RoleId)
                .SetIf(!string.IsNullOrWhiteSpace(model.UserName), a => a.UserName, model.UserName)
                .SetIf(!string.IsNullOrWhiteSpace(model.Password), a => a.Password, Crypto.Md5(model.Password))
                .SetIf(!string.IsNullOrWhiteSpace(model.TrueName), a => a.TrueName, model.TrueName)
                .SetIf(!string.IsNullOrWhiteSpace(model.Email), a => a.Email, model.Email)
                .SetIf(!string.IsNullOrWhiteSpace(model.Phone), a => a.Phone, model.Phone)
                .SetIf(id > 1, a => a.State, (int)model.State)
                .Set(a => a.UpdateTime, DateTime.Now)
                .Where(a => a.Id == id).ExecuteAffrows();
            // 更新;
            this.UpdateSession(id);
            BaseController.UpdateUserList(_fsql);
            return Json(new ResponseResult<string>(true, "更新成功."));
        }

        // POST: UserController/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            if (id > 1)
            {
                _fsql.Update<Employ>()
                    .Set(a => a.UpdateTime, DateTime.Now)
                    .Set(a => a.IsDeleted, true)
                    .Where(a => a.Id == id).ExecuteAffrows();
                BaseController.UpdateUserList(_fsql);
            }
            return Json(new ResponseResult<string>(true, "删除成功."));
        }
    }
}
